﻿using Cyss.Core.Cache;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cyss.Core.Api
{
    /// <summary>
    /// 缓存Action 目前只支持 get 缓存
    /// </summary>
    public class CacheAttribute : Attribute, IActionFilter
    {
        private string CacheKey = "AcitonCache:{0}.{1}.{2}";

        /// <summary>
        /// 过期时间
        /// </summary>
        public int cacheTime { set; get; }

        private IStaticCacheManager _staticCacheManager { set; get; }

        public CacheAttribute()
        {
            this.cacheTime=cacheTime;
            _staticCacheManager =IOCEngine.Resolve<IStaticCacheManager>();
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            var response = context.Result.GetPropertieValue("Value");
            var IsSuccess = Convert.ToBoolean(response.GetPropertieValue("IsSuccess"));
            if (IsSuccess)
            {
                var key = GetCacheKey(context);
                _staticCacheManager.Set(key, response, cacheTime);
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var CacheKey = GetCacheKey(context);
            if (_staticCacheManager.IsSet(CacheKey))
            {
                var obj = _staticCacheManager.Get<object>(CacheKey);
                context.Result = new JsonResult(obj);
                return;
            }
        }

        /// <summary>
        /// 生成缓存key
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCacheKey(ActionExecutingContext context)
        {;
            return string.Format(CacheKey, context.RouteData.Values["controller"].ToString(), context.RouteData.Values["action"].ToString(), context.ActionArguments.Values.FormatParameters());
        }

        /// <summary>
        /// 生成缓存key
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string GetCacheKey(ActionExecutedContext context)
        {
            //请求类各个字段的值
            Dictionary<string, object> parmsObj = new Dictionary<string, object>();
            foreach (var item in context.ModelState)
            {
                parmsObj.Add(item.Key, item.Value.RawValue);
            }
            return string.Format(CacheKey, context.RouteData.Values["controller"].ToString(), context.RouteData.Values["action"].ToString(), parmsObj.Values.FormatParameters());
        }
    }
}
